<?php
@date_default_timezone_set("Asia/Shanghai");
//@file_put_contents("/home/siplogin.log",print_r($_REQUEST,true)."\n",FILE_APPEND);
$host="localhost";
$user="root";
$password="";
$database="fscall";
@require_once '/etc/license.php';
class Helper_crypt3des {
	var $key;
	var $iv;
	function __construct($key, $iv){
		$this->key = $key;
		$this->iv = $iv;
	}

	function encrypt($input){
		$size = mcrypt_get_block_size(MCRYPT_3DES,MCRYPT_MODE_CBC);
		$input = $this->pkcs5_pad($input, $size);
		$key = str_pad($this->key,24,'0');
		$td = mcrypt_module_open(MCRYPT_3DES, '', MCRYPT_MODE_CBC, '');
		if( $this->iv == '' )
		{
			$iv = @mcrypt_create_iv (mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
		}
		else
		{
			$iv = $this->iv;
		}
		@mcrypt_generic_init($td, $key, $iv);
		$data = mcrypt_generic($td, $input);
		mcrypt_generic_deinit($td);
		mcrypt_module_close($td);
		$data = base64_encode($data);
		return $data;
	}

	function decrypt($encrypted){
		$encrypted = base64_decode($encrypted);
		$key = str_pad($this->key,24,'0');
		$td = mcrypt_module_open(MCRYPT_3DES,'',MCRYPT_MODE_CBC,'');
		if( $this->iv == '' )
		{
			$iv = @mcrypt_create_iv (mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
		}
		else
		{
			$iv = $this->iv;
		}
		$ks = mcrypt_enc_get_key_size($td);
		@mcrypt_generic_init($td, $key, $iv);
		$decrypted = mdecrypt_generic($td, $encrypted);
		mcrypt_generic_deinit($td);
		mcrypt_module_close($td);
		$y=$this->pkcs5_unpad($decrypted);
		return $y;
	}

	function pkcs5_pad ($text, $blocksize) {
		$pad = $blocksize - (strlen($text) % $blocksize);
		return $text . str_repeat(chr($pad), $pad);
	}

	function pkcs5_unpad($text){
		$pad = ord($text{strlen($text)-1});
		if ($pad > strlen($text)) {
			return false;
		}
		if (strspn($text, chr($pad), strlen($text) - $pad) != $pad){
			return false;
		}
		return substr($text, 0, -1 * $pad);
	}

	function PaddingPKCS7($data) {
		$block_size = mcrypt_get_block_size(MCRYPT_3DES, MCRYPT_MODE_CBC);
		$padding_char = $block_size - (strlen($data) % $block_size);
		$data .= str_repeat(chr($padding_char),$padding_char);
		return $data;
	}
}
class NTS_Application
{
	/**
	 * 输出
	 * @param string $msg
	 */
	public static function response($msg)
	{
		exit($msg);
	}
	/**
	 * 效验是否包含正版关键字正版软件
	 */
	public static function check_defined()
	{
		if(!defined("NTS_VERSION"))self::response("授权失败1");
		if(!defined("NTS_LIMIT_EXPDATE"))self::response("授权失败2");
		if(!defined("NTS_APIKEY"))self::response("授权失败3");
		if(!defined("NTS_SECREGKEY"))self::response("授权失败4");
		
		$expdate = NTS_LIMIT_EXPDATE;
		$ip = $_SERVER["SERVER_ADDR"];
		$limit_ip = explode(',', NTS_LIMIT_IP);
		#过期判断
		if(strtotime($expdate) < time())
		{
			//过期
			self::uploadApi("limit/expdate");
			
			self::response("对不起,软件已过期");
		}else if(!in_array($ip, $limit_ip))
		{
			//未授权
			self::uploadApi("limit/ip");
			
			self::response("服务器IP未授权");
		}
	}
	
	
	/**
	 * 上传信息到控制中心
	 */
	public static function uploadApi($method,$param = array())
	{
		$host = "http://api.docall100.com/".$method;
		$data = array(
				'NTS_VERSION'=>NTS_VERSION,
				);
		if(count($param) > 0)$data = array_merge($data,$param);
		$data['timeline'] = time();
		$queryString = http_build_query($data);
		$encode = new Helper_crypt3des(NTS_SECREGKEY,"88888888");
		$queryString = $encode->encrypt($queryString);
		$queryString = "NTS_APIKEY=".NTS_APIKEY."&t=".time()."&v=".NTS_VERSION."&s=".$queryString;
		$result = self::request_by_curl($host, $queryString);
	}
	
	public static function request_by_curl($remote_server, $post_string) {
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $remote_server);
		curl_setopt($ch, CURLOPT_POSTFIELDS,  $post_string);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_USERAGENT, "NTS V".NTS_VERSION);
		$data = curl_exec($ch);
		curl_close($ch);
	
		return $data;
	}
	
}
#
NTS_Application::check_defined();
$ip = isset($_REQUEST['sip_auth_realm']) ? trim($_REQUEST['sip_auth_realm']):'';
if(defined("NTS_DIRECT_OPEN") && defined("NTS_DIRECT_IP") && NTS_DIRECT_OPEN  )
{
	if($ip <> defined("NTS_DIRECT_IP"))exit('IP未授权');
}else{
	exit('未打开直播');
}


#sip_user_agent = **#agent_id
$userAgent = trim($_REQUEST['sip_user_agent']);
$userAgent = str_replace('/','',$userAgent);
if(strpos($userAgent,' ') !== false)
{
	$split = explode(' ',$userAgent);
	if(count($split) == 2)
	{
		$userAgent = $split[0];
	}
}
if(strpos($userAgent, '@') === false){
    $userAgent = explode('_iPhone', $userAgent);
    $userAgent = $userAgent[0];
    $agentget = explode('_', $_REQUEST['sip_request_user']);
    $agentid= $agentget[0];
}else{
    $userAgent = explode('@', $userAgent);
    if(count($userAgent) <> 2)
    {
    	printf("error agent format");
    	exit ();
    }
    $agentid = intval($userAgent[1]);
    $userAgent = $userAgent[0];
}
$username = trim($_REQUEST['sip_auth_username']);
$ip = trim($_REQUEST['ip']);

if(strlen($ip) < 7 || strlen($ip)> 15  )
{
	exit('error format ip');
}


if(strlen($username) < 10 || strlen($username)> 15  )
{
	exit('error format username');
}
$cacheId = sprintf("%s-%s-%d",$userAgent,$username,$agentid);
//$cacheId = sprintf("%s-%s-%s-%s-%d",$userAgent,$username,$_REQUEST['sip_auth_realm'],$ip,$agentid);
$cacheId = md5($cacheId);
$redis = new Redis();

$redis->connect('127.0.0.1',6377);
$data = $redis->get($cacheId);
if($data == false)
{
    $dbh = new mysqli($host, $user, $password, $database);
    if (mysqli_connect_errno())
    {
        printf("Connect failed: %s\n", mysqli_connect_error());
        exit ();
    }
    $sql="call auth_user_new('".$userAgent."','".$username."','".$_REQUEST['sip_auth_realm']."','".$ip."',{$agentid})";
    $user_type=0;
    $pwd='dasdMbsad9';
    if ($result_set = $dbh->query($sql))
    {
        while ($row = $result_set->fetch_row())
        {
            $user_type=$row[0];
            if(isset($row[1]))$pwd=$row[1];
        }
        mysqli_free_result($result_set);
        //set data
        $data = "{$user_type},{$pwd}";
        
        $redis->set($cacheId,$data,86400*30);
    }
    else
    {
        printf("<p>Error:%d (%s) %s\n", mysqli_errno($dbh),
        mysqli_sqlstate($dbh), mysqli_error($dbh));
        $redis->close();
        mysqli_close($dbh);
        exit();
    }
    mysqli_close($dbh);
    
}else{
    $data = explode(',', $data);
    if(count($data) == 2){
        $user_type = $data[0];
        $pwd = $data[1];
    }else{
        $redis->close();
        exit('errx');
    }
}

    
    $redis->close();

unset($redis);


//if($_REQUEST['sip_auth_username']=='18628180090')
//$user_type=2;
$context="default";
$pwdxml="";
if ($user_type==2)
{
	$context="incoming";
}
else if($user_type==1)
{
$pwdxml=<<<pwd
<params><param name="password" value="$pwd" /></params>
pwd;
}
else
{
	exit(0);
}
$dir="directory";
$domain=$_REQUEST['domain'];
$auth_username=$_REQUEST['sip_auth_username'];
$xml=<<<user
<document type="freeswitch/xml">
<section name="directory">
<domain name="$domain">
<user id="$auth_username" cacheable="true">
$pwdxml
<variables>
<variable name="user_context" value="$context"/>
</variables>
</user>
</domain>
</section>
</document>
user;
echo $xml;
?>